package com.example.demo.service.impl;

import com.example.demo.dao.TeacherDao;
import com.example.demo.entity.TeacherBean;
import com.example.demo.service.TeacherService;
import com.example.demo.util.EduJwtUtil;
import com.example.demo.util.PageEntity;
import com.example.demo.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public List<TeacherBean> all() {
        return teacherDao.getAll();
    }

    @Override
    public Integer add(TeacherBean teacherBean) {
        return teacherDao.insert(teacherBean);
    }

    @Override
    public Integer update(TeacherBean teacherBean) {
        return teacherDao.edit(teacherBean);
    }

    @Override
    public Integer delete(Integer id) {
        return teacherDao.del(id);
    }

    @Override
    public TeacherBean one(Integer id) {
        return teacherDao.getOne(id);
    }

    @Override
    public ResponseEntity login(TeacherBean loginTeacher) {
        HashMap<String, String> data = new HashMap<>();
        TeacherBean teacher = teacherDao.getByUsername(loginTeacher.getUsername());
        
        if (teacher != null) {
            String password = teacher.getPassword();
            if (password.equals(loginTeacher.getPassword())) {
                // 账号密码正确
                data.put("id", teacher.getId().toString());
                data.put("name", teacher.getName());
                data.put("username", teacher.getUsername());
                // 生成Token
                String token = EduJwtUtil.createTeacherToken(teacher);
                data.put("token", token);
                return new ResponseEntity(200, "登录成功", data);
            }
        }
        return new ResponseEntity(500, "账号或密码不正确", null);
    }

    @Override
    public PageEntity list(Integer pageNo, Integer pageSize, String name, String zhicheng, String sortOrder) {
        // 根据页码计算跳过的记录数
        Integer jump = (pageNo - 1) * pageSize;
        
        Integer count = teacherDao.getCount(name, zhicheng);
        List<TeacherBean> rows = teacherDao.getPage(jump, pageSize, name, zhicheng, sortOrder);
        
        return new PageEntity<List>(rows, count);
    }
}
